package com.leetcode.partition8;

import com.leetcode.common.ListNode;

/**
 * @author `RKC`
 * @date 2021/9/22 8:23
 */
public class LC725分隔链表 {

    public static ListNode[] splitListToParts(ListNode head, int k) {
        int len = 0;
        ListNode[] answer = new ListNode[k];
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        cur = head;
        int quotient = len / k, remainder = len % k;            //计算出每组大小和余数
        System.out.println("每组个数：" + quotient);
        System.out.println("余数：" + remainder);
        for (int i = 0; i < k && cur != null; i++) {               //遍历结果组
            answer[i] = cur;
            cur = cur.next;
            ListNode temp = answer[i];
            //cur指针根据每组大小和余数向后移动
            int step = quotient;
            if (remainder-- > 0) step++;
            while (step > 1 && cur != null) {
                temp.next = cur;
                temp = temp.next;
                cur = cur.next;
                step--;
            }
            temp.next = null;
        }
        return answer;
    }

    public static void main(String[] args) {
        ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(3)));
//        ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5,
//                new ListNode(6, new ListNode(7, new ListNode(8, new ListNode(9, new ListNode(10))))))))));
        ListNode[] res = splitListToParts(head1, 8);
        for (ListNode val : res) {
            ListNode temp = val;
            System.out.print("[");
            while (temp != null) {
                System.out.print(temp.val + ", ");
                temp = temp.next;
            }
            System.out.print("]\n");
        }
    }
}
